var express = require("express");
var router = express.Router();
var httpRequire = require('request');
var querystring = require('querystring');
var config = require('../../app/conf/config.json');
var log4js = require('log4js');
var logger = log4js.getLogger();

router.post("/guest", function(req, res) {
    console.log("/auth/guest");
});

router.get("/test", function(req, res) {
    // var url="请求url";
    // var requestData="上送的数据";
    // httpRequire({
    //     url: url,
    //     method: "POST",
    //     json: true,
    //     headers: {
    //         "content-type": "application/json",
    //     },
    //     body: JSON.stringify(requestData)
    // }, function(error, response, body) {
    //     if (!error && response.statusCode == 200) {
    //         console.log(body) // 请求成功的处理逻辑
    //     }
    // });
    console.log("/auth/test");
    res.write("hello, test");
    res.end();
});

router.post("/wechatLogin", function(req, res) {
    console.log("/auth/wechatLogin");
    var postData = '';
    req.setEncoding("utf8");
    req.on('data', function (chunk) {
        postData += chunk;
    });

    req.on('end', function () {
        /*
        * https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        * playerData2GameServer.openid = xxx
        * playerData2GameServer.expires_in = xxx
        * playerData2GameServer.access_token = xxx
        * playerData2GameServer.userDetails = {
            "openid":"OPENID",
            "nickname":"NICKNAME",
            "sex":1,
            "province":"PROVINCE",
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl": "http://wx.qlogo.cn/mmopen/x/0",
            "privilege":[
            "PRIVILEGE1",
            "PRIVILEGE2"
            ],
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }
        * */
        postData = JSON.parse(postData);
        var authorizationCode = postData.authorizationCode;
        var appid = postData.appid;
        var userChannel = postData.channel;
        var wxPayConfig = config.wxPayParams[appid];
        var secret = wxPayConfig.appSecret;
        var queryParams = "appid=" + appid + "&secret=" + secret + "&code=" + authorizationCode + "&grant_type=authorization_code";
        var url = config.wxLoginUrl + queryParams;

        var option = {
            url: url,
            method: 'GET',
            timeout: 60000
        };

        // 1.通过CODE获取token
        logger.info("send to tencent get token: %s", url);
        httpRequire(option, function (err, response, body) {
            if(!!err){
                logger.error("login request callback error: error: %s", err);
                res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                res.end();
                return;
            }
            if(!body){
                logger.error("login request callback error, body is empty");
                res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                res.end();
                return;
            }
            logger.info("login request callback: %s", body);
            var wxLoginResult = JSON.parse(body);
            if(wxLoginResult.hasOwnProperty("errcode")){
                logger.error("login request callback with error code: error: %s", JSON.stringify(body));
                res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                res.end();
                return;
            }
            if(!wxLoginResult.hasOwnProperty("access_token")){
                logger.error("login request callback without access_token");
                res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                res.end();
                return;
            }
            // 2. 向腾讯获取用户个人信息
            var detailUrl = config.wxGetDetailUrl + "access_token=" + wxLoginResult.access_token + "&openid=" + wxLoginResult.openid;
            var getUserDetailOption = {
                url: detailUrl,
                method: 'GET',
                timeout: 60000
            };
            logger.info("getUserDetailOption: %s", detailUrl);
            httpRequire(getUserDetailOption, function (errGetUserDetail, resGetUserDetail, bodyGetUserDetail) {
                if(!!errGetUserDetail){
                    logger.error("getUserDetail request callback error: %s", errGetUserDetail);
                    res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                    res.end();
                    return;
                }
                if(!bodyGetUserDetail){
                    logger.error("getUserDetail request callback error, body is empty");
                    res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                    res.end();
                    return;
                }
                logger.info("getUserDetail callback resGetUserDetail : %s", resGetUserDetail);
                var getUserDetailResult = JSON.parse(bodyGetUserDetail);
                if(getUserDetailResult.hasOwnProperty("errcode")){
                    logger.error("getUserDetail callback with error code: %s", getUserDetailResult.errcode);
                    res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                    res.end();
                    return;
                }
                // 3.给game服发送getToken, 创建用户或者更新token
                var getTokenParams = {};
                getTokenParams.openid = getUserDetailResult.openid;
                getTokenParams.userChannel = userChannel;
                getTokenParams.nickname = getUserDetailResult.nickname;
                getTokenParams.unionid = getUserDetailResult.unionid;
                getTokenParams.gender = parseInt(getUserDetailResult.sex);
                getTokenParams.avatar = getUserDetailResult.headimgurl;
                getTokenParams.token = wxLoginResult.access_token;
                getTokenParams.type = 2; //微信
                getTokenParams = querystring.stringify(getTokenParams); //encodeURI
                var getTokenUrl = config.gameServerLoginUrl + '?' + getTokenParams;
                logger.info("getToken getTokenUrl: %s", getTokenUrl);

                var loginOption = {
                    url: getTokenUrl,
                    method: 'GET',
                    timeout: 60000
                };

                httpRequire(loginOption, function (errFromGameServer, resFromGameServer, bodyFromGameServer) {
                    if(!!errFromGameServer){
                        logger.error("getToken callback error: %s", JSON.stringify(errFromGameServer));
                        res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                        res.end();
                        return;
                    }
                    if(!bodyFromGameServer){
                        logger.error("getToken callback error, body is empty");
                        res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                        res.end();
                        return;
                    }
                    logger.info("getToken callback body: %s", JSON.stringify(bodyFromGameServer));
                    bodyFromGameServer = JSON.parse(bodyFromGameServer);
                    if(bodyFromGameServer.resultCode !== 0){
                        logger.error("getToken callback with resultCode: %s", bodyFromGameServer.resultCode);
                        res.write(JSON.stringify({resultCode : 100, msg : 'Failed'}));
                        res.end();
                        return;
                    }
                    var detail = {};
                    detail.resultCode = 0;
                    detail.token = wxLoginResult.access_token;
                    logger.info("callback to client: %s", JSON.stringify(detail));
                    res.write(JSON.stringify(detail));
                    res.end();
                });
            });
        });
    });
});

module.exports = router;